#include <conio.h>
#include "hikari.h"

#pragma comment(lib, "irrlicht.lib")
const int UPDATE_FPS=80;

wstring getSceneName(){
	char buff[1024];
    FILE *f = fopen("scene.dbg", "r");
	if(f==0){
		printf("Cannot open file scene.dbg");
		return L"";
	}
    fgets(buff, 1024, f);
	fclose(f);
	std::string path(buff);
	wstring wpath=Utils::string_to_wstring(path);
	return wpath;
}

void updateUpdateableObjects(HikariContext*context){
	std::list<HObj*>&updateableObjects=context->getListOfUpdateableObjects();
	for(std::list<HObj*>::iterator i=updateableObjects.begin();i!=updateableObjects.end();i++){
		HObj*object=*i;
		vector<hComponent*>components=object->getComponentList();
		int length=components.size();
		for(int i=0;i<length;i++){
			hComponent*component=components[i];
			component->update(context, object);
		}
	}
}

int main(int argc, char* argv[]){
	IrrlichtInitializer initializer;
	IrrlichtDevice*device=initializer.createIrrlichtDevice(L"game.hikari");
	if(device==0){
		printf("Cannot initialize engine device\n");
		_getch();
		return 1;
	}

	HikariEventReceiver eventReceiver;
	HikariContext context(device, &eventReceiver);
	gui::IGUIEnvironment*gui=device->getGUIEnvironment();
	device->setEventReceiver(&eventReceiver);
	wstring sceneName=getSceneName();
	if(Utils::equal(sceneName,L"")){
		_getch();
		return 1;
	}

	bool result=Hikari::loadScene(sceneName, &context);
	if(result==false){
		printf("Error while loading the scene\n");
		return 1;
	}

	u32 currentTime=device->getTimer()->getRealTime();
	u32 timeOfLastUpdate=currentTime;
	int frameCounter=0;
	float milliseccondsPerUpdate=1000.f/UPDATE_FPS;

	while(context.getDevice()->run()){
		u32 newTime=device->getTimer()->getRealTime();
		const f32 frameDeltaTime = (f32)(newTime - currentTime) / 1000.f; // Time in seconds
		context.setCurrentTime(currentTime);
		context.setDeltaTime(frameDeltaTime);

		if((currentTime-timeOfLastUpdate)>=milliseccondsPerUpdate){
			updateUpdateableObjects(&context);
			timeOfLastUpdate=currentTime;
		}

		//RENDERING
		context.getDriver()->beginScene(true, true, SColor(255,255,255,255));
		context.getSceneManager()->drawAll();
		gui->drawAll();
		context.getDriver()->endScene();
		frameCounter++;
		currentTime=newTime;
	}

	return 0;
}